﻿using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;
using Unity.Mathematics;

namespace Game.FlowField.Burst
{
    [BurstCompile]
    public struct UnitRemovingJob : IJob
    {
        [ReadOnly]
        public int2 MapSize;

        /// <summary>
        /// Input
        /// </summary>
        [ReadOnly]
        public NativeArray<int2> AddingGridIndex2Ds;

        /// <summary>
        /// Input Output
        /// </summary>
        public NativeArray<int> GridOccupies;

        /// <summary>
        /// Input Output
        /// </summary>
        public NativeArray<FlexibleArray<Unit>> Units;

        [BurstDiscard]
        public void WrapData(MapData mapData, NativeArray<int2> addingGridIndex2Ds, NativeArray<FlexibleArray<Unit>> units)
        {
            this.MapSize = mapData.Size;
            this.AddingGridIndex2Ds = addingGridIndex2Ds;
            this.GridOccupies = mapData.GridOccupies;
            this.Units = units;
        }

        [BurstCompile]
        public void Execute()
        {
            var units = this.Units[0];

            for (int i = 0; i < this.AddingGridIndex2Ds.Length; i++)
            {
                var addingIndex2D = this.AddingGridIndex2Ds[i];
                if (!MapDataUtil.IsInsideMap(addingIndex2D, this.MapSize))
                    continue;

                var addingIndex = MapDataUtil.ConvertIndex2D2Index(addingIndex2D, this.MapSize);
                var occupy = this.GridOccupies[addingIndex];
                if (occupy <= 0)
                    continue;

                for (int j = 0; j < units.Length; j++)
                {
                    var unit = units.Array[j];
                    if (unit.GridIndexTo == addingIndex && unit.IsAlive)
                    {
                        unit.ResetAsDeadOne();
                        var array = units.Array;
                        array[j] = unit;
                        this.GridOccupies[addingIndex] = occupy - 1;
                    }
                }
            }

            this.Units[0] = units;
        }
    }
}